package com.imooc.hadoop.mapreduce.sort;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Objects;

/**
 * @program: hadoop_db
 * @description: SortWritable
 * @author: zengchen
 * @create: 2021-03-28 21:18
 **/
public class SortWritable implements WritableComparable {
    private Long first;
    private Long second;

    public SortWritable(){

    }

    public SortWritable(Long first, Long second) {
        this.first = first;
        this.second = second;
    }

    public Long getFirst() {
        return first;
    }

    public void setFirst(Long first) {
        this.first = first;
    }

    public Long getSecond() {
        return second;
    }

    public void setSecond(Long second) {
        this.second = second;
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeLong(this.first);
        dataOutput.writeLong(this.second);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        this.first = dataInput.readLong();
        this.second = dataInput.readLong();
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if (!(obj instanceof SortWritable)) return false;

        SortWritable sortWritable = (SortWritable) obj;
        return compareLong(this.getFirst(), sortWritable.getFirst())
                && compareLong(this.getSecond(), sortWritable.getSecond());
    }

    private boolean compareLong(Long l1, Long l2) {
        return l1.longValue() == l2.longValue();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getFirst(), getSecond());
    }

    @Override
    public int compareTo(Object obj) {
        SortWritable targetSort = (SortWritable) obj;
        int firResult = this.getFirst().intValue() - targetSort.getFirst().intValue();
        if(firResult != 0){
            return firResult;
        }else{
            return targetSort.getSecond().intValue() - this.getSecond().intValue();
        }
    }
}
